package com.aids_malaria.ui.setting;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.aids_malaria.R;
import com.aids_malaria.app.Constant;
import com.aids_malaria.base.BaseActivity;
import com.aids_malaria.db.DBManager;
import com.aids_malaria.http.response.Pad;
import com.aids_malaria.http.BaseObserver;
import com.aids_malaria.http.RetrofitFactory;
import com.aids_malaria.http.RxScheduler;
import com.aids_malaria.http.api.RetrofitApi;
import com.aids_malaria.util.AuthUtil;
import com.aids_malaria.util.DisplayUtil;
import com.aids_malaria.util.GsonUtil;
import com.aids_malaria.util.ResourceUtil;
import com.aids_malaria.util.StringUtil;
import com.aids_malaria.util.ToastUtil;
import com.aids_malaria.widget.dialog.ConfirmDialog;
import com.aids_malaria.widget.titlebar.TitleBar;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class PadManagerCreateEditActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    TitleBar title_bar;
    @BindView(R.id.tv_sequence_number)
    TextView tv_sequence_number;
    @BindView(R.id.et_pad_id)
    EditText et_pad_id;
    @BindView(R.id.et_remark)
    EditText et_remark;
    @BindView(R.id.tv_confirm)
    TextView tv_confirm;

    public static final String KEY_IS_CREATE = "is_create";
    public static final String KEY_SEQ = "seq";
    public static final String KEY_PAD = "pad";

    private boolean isCreate;
    private Pad mPad;
    private String mSeq;

    private String prePadid;
    private String preremark;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_pad_manager_create_edit;
    }

    @Override
    protected void initData() {
        super.initData();
        Bundle bundle = getIntent().getExtras();
        if(null != bundle){
            isCreate = bundle.getBoolean(KEY_IS_CREATE);
        }
        if(isCreate){
            initTitleBar(title_bar,getString(R.string.pad_sequence_number_create));
            mPad = new Pad();
            mSeq = bundle.getString(KEY_SEQ);
            tv_sequence_number.setText(mSeq);
        }else{
            initTitleBar(title_bar,getString(R.string.pad_sequence_number_edit));
            mPad = (Pad) bundle.getSerializable(KEY_PAD);
            if (mPad != null){
                tv_sequence_number.setText(mPad.getSeq());
                et_remark.setText(mPad.getMemo());
                et_pad_id.setText(mPad.getPad_id());

                preremark =  mPad.getMemo();
                prePadid = mPad.getPad_id();
            }
        }

    }
    @Override
    public void back() {

        Boolean showTip = (isCreate && (et_pad_id.getText().toString().trim().length() > 0 || et_remark.getText().toString().trim().length() > 0)
        || (!isCreate && (!preremark.equals(et_remark.getText().toString().trim()) || !prePadid.equals(et_pad_id.getText().toString().trim()))));

        if (!showTip){finish();return;}

        if (isCreate){
            if (!AuthUtil.isHaveInsertAuthByCode(Constant.SETTING_PAD_SEQ)){
                return;
            }
        }else{
            if (!AuthUtil.isHaveUpdateAuthByCode(Constant.SETTING_PAD_SEQ)){
                return;
            }
        }

        String tipString = isCreate ? getString(R.string.tip_data_add):getString(R.string.tip_data_modify);
        ConfirmDialog.newInstance(true, getString(R.string.hint), tipString)
                .setCancelConfirOption(new ConfirmDialog.CancelConfirOption() {
                    @Override
                    public void cancel() {

                    }

                    @Override
                    public void confirm() {
                        finish();
                    }
                })
                .setOutCancel(true)
                .setWidth(DisplayUtil.px2dp((int) (DisplayUtil.getWindowWidth() * 0.5)))
                .show(getSupportFragmentManager());
    }

    @OnClick({R.id.tv_confirm})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.tv_confirm:
                String padId = et_pad_id.getText().toString().trim();
                String remark = et_remark.getText().toString().trim();
                if (TextUtils.isEmpty(padId) || StringUtil.isEmpty(remark)){
                    ToastUtil.showToast(getString(R.string.input_null));
                    return;
                }
                mPad.setPad_id(padId);
                mPad.setMemo(remark);
                if(isOnLine()){
                    String dataJson = GsonUtil.beanToJson(mPad);
                    if (isCreate){
                        if (!AuthUtil.isHaveInsertAuthByCode(Constant.SETTING_PAD_SEQ)){
                            ToastUtil.showNoPermission();
                            return;
                        }
                        savePad("1",dataJson);
                    }else {
                        if (!AuthUtil.isHaveUpdateAuthByCode(Constant.SETTING_PAD_SEQ)){
                            ToastUtil.showNoPermission();
                            return;
                        }
                        savePad("2",dataJson);
                    }
                }else{
//                    LiteOrmUtil.getLiteOrm().insert(mPad);
                    DBManager.get().padDao().insert(mPad);
                    ToastUtil.showToast(getString(R.string.operate_success));
                    finish();
                }
                break;
        }
    }

    /**
     * 新增、编辑pad    保存类型 1插入 2更改 3 删除
     * @param type
     * @param data
     */
    private void savePad(String type,String data){
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), data);
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).savePad(type,requestBody)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<Object>() {

                    @Override
                    protected void onStart() {
                        getLoadingDialog().show();
                    }

                    @Override
                    protected void onSuccess(Object object) throws Exception {
                        ToastUtil.showToast(ResourceUtil.getString(R.string.operate_success));
                        finish();
                    }

                    @Override
                    protected void onFinish() {
                        getLoadingDialog().dismiss();
                    }
                });
    }

}
